from WinningEvaluation import WinningEvaluation
from Chessnut import Game

import random
import copy

def StrGame(game):
    game = str(game)
    game = list(game)
    out = ""
    i = 0
    while True:
        if game[i] != " ":
            out = out + str(game[i])
            i += 1
        else:
            break
    return out
    
def op(playerside):
    if playerside == "b":
        return "w"
    if playerside == "w":
        return "b"

def GiveBestMove(chessgame, playerside, deep):
    if deep == 0:
        copygame = copy.deepcopy(chessgame)
        moves = chessgame.get_moves()
        move = random.choice(moves)
        copygame.apply_move(move)
        back = [move, WinningEvaluation(StrGame(copygame))]
        return back
    if deep == 1:
        moves = chessgame.get_moves()
        movescrs = []
        for move in moves:
            #print(move)
            copyone = copy.deepcopy(chessgame)
            #print(move)
            copyone.apply_move(move)
            movescrs.append(WinningEvaluation(StrGame(copyone)))
        i = 0
        for scr in movescrs:
            if playerside == "b":
                if scr > min(movescrs):
                    movescrs.remove(scr)
                    del moves[i]
            if playerside == "w":
                if scr < max(movescrs):
                    movescrs.remove(scr)
                    del moves[i]
            i += 1
            
        back = [random.choice(moves), max(movescrs)]
        return back
    else:
        movesscrs = []
        nextmoves = []
        moves = chessgame.get_moves()
        for move in moves:
            copygame = copy.deepcopy(chessgame)
            copygame.apply_move(move)
            nextmove = GiveBestMove(copygame, op(playerside), deep-1)
            movesscrs.append(nextmove[1])
            nextmoves.append(nextmove[0])
        i = 0
        for scr in movesscrs:
            if playerside == "b":
                if scr > min(movesscrs):
                    movesscrs.remove(scr)
                    del nextmoves[i]
            if playerside == "w":
                if scr < max(movesscrs):
                    movesscrs.remove(scr)
                    del nextmoves[i]
            i += 1
        
        back = [random.choice(nextmoves), max(movesscrs)]
        return back